/**
 * 详情页面脚本
 */


document.addEventListener("DOMContentLoaded", () => {
  // 获取媒体ID
  const urlParams = new URLSearchParams(window.location.search)
  const mediaId = urlParams.get("id")

  if (!mediaId) {
    showError("缺少媒体ID")
    return
  }

  // 加载媒体详情
  loadMediaDetail(Number.parseInt(mediaId))

  // 初始化收藏按钮
  initFavoriteButton(Number.parseInt(mediaId))
})

/**
 * 加载媒体详情
 * @param {number} id 媒体ID
 */
async function loadMediaDetail(id) {
  const detailLoading = document.getElementById("detailLoading")
  const detailContainer = document.getElementById("detailContainer")
  const detailError = document.getElementById("detailError")
  const errorText = document.getElementById("errorText")

  try {
    // 显示加载中
    if (detailLoading) detailLoading.style.display = "flex"
    if (detailContainer) detailContainer.style.display = "none"
    if (detailError) detailError.style.display = "none"

    // 获取活跃源
    const activeSource = AppConfig.getActiveSource()
    if (!activeSource) {
      throw new Error("请先添加媒体源")
    }

    // 获取媒体详情
    const media = await API.getMediaDetail(activeSource, id)
    if (!media) {
      throw new Error(`无法找到ID为 ${id} 的内容`)
    }

    // 渲染媒体详情
    renderMediaDetail(media)

    // 隐藏加载中，显示详情
    if (detailLoading) detailLoading.style.display = "none"
    if (detailContainer) detailContainer.style.display = "block"
  } catch (error) {
    console.error("加载媒体详情失败:", error)

    // 隐藏加载中和详情，显示错误
    if (detailLoading) detailLoading.style.display = "none"
    if (detailContainer) detailContainer.style.display = "none"
    if (detailError) detailError.style.display = "flex"
    if (errorText) errorText.textContent = error.message || "加载失败，请重试"
  }
}

/**
 * 渲染媒体详情
 * @param {Object} media 媒体详情
 */
function renderMediaDetail(media) {
  // 设置标题
  document.title = `${media.vod_name} - 飞牛影视`

  // 设置背景图
  const detailBackdrop = document.getElementById("detailBackdrop")
  if (detailBackdrop) {
    detailBackdrop.style.backgroundImage = `url(${media.vod_pic || "images/placeholder.jpg"})`
  }

  // 设置海报
  const mediaPoster = document.getElementById("mediaPoster")
  if (mediaPoster) {
    mediaPoster.src = media.vod_pic || "images/placeholder.jpg"
    mediaPoster.alt = media.vod_name
  }

  // 设置标题
  const mediaTitle = document.getElementById("mediaTitle")
  if (mediaTitle) {
    mediaTitle.textContent = media.vod_name
  }

  // 设置元数据
  const detailMeta = document.getElementById("detailMeta")
  if (detailMeta) {
    let metaHTML = ""

    if (media.vod_year) {
      metaHTML += `
        <div class="detail-meta-item">
          <i class="ri-calendar-line"></i>
          <span>${media.vod_year}</span>
        </div>
      `
    }

    if (media.type_name) {
      metaHTML += `
        <div class="detail-meta-item">
          <i class="ri-price-tag-3-line"></i>
          <span>${media.type_name}</span>
        </div>
      `
    }

    if (media.vod_area) {
      metaHTML += `
        <div class="detail-meta-item">
          <i class="ri-map-pin-line"></i>
          <span>${media.vod_area}</span>
        </div>
      `
    }

    if (media.vod_remarks) {
      metaHTML += `
        <div class="detail-meta-item">
          <i class="ri-time-line"></i>
          <span>${media.vod_remarks}</span>
        </div>
      `
    }

    detailMeta.innerHTML = metaHTML
  }

  // 设置演职员信息
  const detailCredits = document.getElementById("detailCredits")
  if (detailCredits) {
    let creditsHTML = ""

    if (media.vod_director) {
      creditsHTML += `
        <div class="detail-credit-item">
          <span class="detail-credit-label">导演:</span>
          <span class="detail-credit-value">${media.vod_director}</span>
        </div>
      `
    }

    if (media.vod_actor) {
      creditsHTML += `
        <div class="detail-credit-item">
          <span class="detail-credit-label">演员:</span>
          <span class="detail-credit-value">${media.vod_actor}</span>
        </div>
      `
    }

    detailCredits.innerHTML = creditsHTML
  }

  // 设置播放按钮
  const playButton = document.getElementById("playButton")

  // 解析播放地址
  const playInfos = API.parsePlayUrls(media.vod_play_from, media.vod_play_url)
  const hasPlayUrls = playInfos.length > 0 && playInfos[0].urls.length > 0

  // 获取第一个播放地址
  const firstPlayUrl = hasPlayUrls ? playInfos[0].urls[0].url : ""
  const firstPlayFrom = hasPlayUrls ? playInfos[0].from : ""

  if (playButton) {
    if (hasPlayUrls) {
      playButton.disabled = false
      playButton.innerHTML = `<i class="ri-play-fill"></i> 立即播放`
      playButton.onclick = () => {
        window.location.href = `play.html?id=${media.vod_id}&from=${firstPlayFrom}&url=${encodeURIComponent(firstPlayUrl)}`
      }
    } else {
      playButton.disabled = true
      playButton.innerHTML = `<i class="ri-play-fill"></i> 暂无播放源`
    }
  }

  // 设置剧情简介
  const detailPlot = document.getElementById("detailPlot")
  if (detailPlot && media.vod_content) {
    detailPlot.innerHTML = `
      <h2><i class="ri-file-list-line"></i> 剧情简介</h2>
      <p>${media.vod_content}</p>
    `
  } else if (detailPlot) {
    detailPlot.style.display = "none"
  }

  // 设置播放列表
  const detailEpisodes = document.getElementById("detailEpisodes")
  if (detailEpisodes && hasPlayUrls) {
    let episodesHTML = `<h2><i class="ri-play-list-line"></i> 播放列表</h2>`

    playInfos.forEach((playInfo, index) => {
      episodesHTML += `
        <div class="episode-source">
          <h3>${playInfo.from}</h3>
          <div class="episode-grid">
      `

      playInfo.urls.forEach((item, idx) => {
        episodesHTML += `
          <a href="play.html?id=${media.vod_id}&from=${playInfo.from}&url=${encodeURIComponent(item.url)}" 
             class="episode-button">
            ${item.name}
          </a>
        `
      })

      episodesHTML += `
          </div>
        </div>
      `
    })

    detailEpisodes.innerHTML = episodesHTML
  } else if (detailEpisodes) {
    detailEpisodes.style.display = "none"
  }
}

/**
 * 初始化收藏按钮
 * @param {number} id 媒体ID
 */
function initFavoriteButton(id) {
  const favoriteButton = document.getElementById("favoriteButton")
  if (!favoriteButton) return

  // 检查是否已收藏
  const isFavorited = API.isFavorite(id)

  // 更新按钮状态
  updateFavoriteButton(favoriteButton, isFavorited)

  // 添加点击事件
  favoriteButton.addEventListener("click", async () => {
    try {
      // 获取活跃源
      const activeSource = AppConfig.getActiveSource()
      if (!activeSource) {
        throw new Error("请先添加媒体源")
      }

      // 获取媒体详情
      const media = await API.getMediaDetail(activeSource, id)
      if (!media) {
        throw new Error(`无法找到ID为 ${id} 的内容`)
      }

      // 切换收藏状态
      if (isFavorited) {
        // 移除收藏
        const success = API.removeFavorite(id)
        if (success) {
          updateFavoriteButton(favoriteButton, false)
          UI.showToast("已移除收藏")
        }
      } else {
        // 添加收藏
        const success = API.addFavorite(media)
        if (success) {
          updateFavoriteButton(favoriteButton, true)
          UI.showToast("已添加到收藏")
        }
      }
    } catch (error) {
      console.error("收藏操作失败:", error)
      UI.showToast(error.message || "操作失败，请重试", "error")
    }
  })
}

/**
 * 更新收藏按钮状态
 * @param {HTMLElement} button 按钮元素
 * @param {boolean} isFavorited 是否已收藏
 */
function updateFavoriteButton(button, isFavorited) {
  if (isFavorited) {
    button.innerHTML = `<i class="ri-heart-fill"></i> 已收藏`
    button.classList.add("btn-primary")
    button.classList.remove("btn-outline")
  } else {
    button.innerHTML = `<i class="ri-heart-line"></i> 收藏`
    button.classList.remove("btn-primary")
    button.classList.add("btn-outline")
  }
}

/**
 * 显示错误信息
 * @param {string} message 错误信息
 */
function showError(message) {
  const detailLoading = document.getElementById("detailLoading")
  const detailContainer = document.getElementById("detailContainer")
  const detailError = document.getElementById("detailError")
  const errorText = document.getElementById("errorText")

  if (detailLoading) detailLoading.style.display = "none"
  if (detailContainer) detailContainer.style.display = "none"
  if (detailError) detailError.style.display = "flex"
  if (errorText) errorText.textContent = message
}

/**
 * 格式化时间为相对时间
 * @param {number} timestamp 时间戳
 * @returns {string} 相对时间
 */
function formatTimeAgo(timestamp) {
  const now = Date.now()
  const diff = now - timestamp

  // 小于1分钟
  if (diff < 60 * 1000) {
    return "刚刚"
  }

  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes}分钟前`
  }

  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  }

  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }

  // 大于30天
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
}
